package com.ybear.citypickerview;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;

import static com.ybear.citypickerview.DialogRecyclerView.STATE.TOP;

public class CityPickerDialog extends Dialog {
    private TextView tvTitle;
    private ImageView ivCloseBtn;
    private CityPickerView cpvCityPicker;

    private View.OnClickListener mOnClickCloseListener;
    private CityPickerView.OnSelectBranchListener mOnSelectBranchListener;

    private boolean enableAutoDismiss = true;
    private boolean enableAutoTopLastDismiss = true;
    private int topScrollY;
    private int topLastDistance = 550;
    private int max = Integer.MAX_VALUE;

    public CityPickerDialog(Context context) {
        super(context, R.style.DialogBottom);
        init();
    }

    private void init() {
        initView();
        initListener();

        Window w = getWindow();
        if( w != null ) {
            int h = getContext().getResources().getDisplayMetrics().heightPixels;
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = h - ( h / 5 );
            lp.windowAnimations = R.style.AnimDialogBottom;
            w.setAttributes( lp );
            w.setBackgroundDrawableResource(R.drawable.shape_dialog);
            w.setGravity(Gravity.BOTTOM);
        }
    }

    @SuppressLint("InflateParams")
    private void initView() {
        View vRoot = View.inflate(getContext(), R.layout.dialog_city_picker, null);
        tvTitle = vRoot.findViewById(R.id.dialog_city_picker_tv_title);
        ivCloseBtn = vRoot.findViewById(R.id.dialog_city_picker_iv_close);
        cpvCityPicker = vRoot.findViewById(R.id.dialog_city_picker_cpv_city_picker);

        setContentView(vRoot);
    }

    private void initListener() {
        ivCloseBtn.setOnClickListener(view -> {
            if( mOnClickCloseListener != null ) mOnClickCloseListener.onClick(view);
            dismiss();
        });
        cpvCityPicker.setOnSelectBranchListener((view, branch, maxBranch) -> {
            if( mOnSelectBranchListener != null ) {
                mOnSelectBranchListener.onBranch(view, branch, maxBranch);
            }
            if( enableAutoDismiss && branch == maxBranch - 1 ) dismiss();
        });

        cpvCityPicker.getDialogRecyclerView().setOnScrollStateListener((state, action, dy, oldY) -> {
            if( !enableAutoTopLastDismiss ) return;
            //处于顶部和弹起s
            if( state == TOP && action == 2 && oldY < dy && topScrollY > dy ) topScrollY = max;
            if( topScrollY == max ) topScrollY = dy;
            if( state == TOP && dy - topScrollY >= topLastDistance ) {
                topScrollY = max;
               if( isShowing() ) dismiss();
            }
        });
    }

    @Override
    public void show() {
        super.show();
        topScrollY = max;
    }

    /**
     * 选择完毕后是否自动关闭。默认启用
     * @param enable    是否自动关闭
     */
    public void setEnableAutoDismiss(boolean enable) {
        enableAutoDismiss = enable;
    }

    /**
     * 到达顶部后自动关闭。默认启用
     * @param enable    是否自动启用
     */
    public void setEnableAutoTopLastDismiss(boolean enable) {
        enableAutoTopLastDismiss = enable;
    }

    /**
     * 到达顶部后自动关闭的距离
     * @param distance  距离
     */
    public void setAutoTopLastDistance(int distance) {
        topLastDistance = distance;
    }

    /**
     * 设置关闭按钮图标
     * @param resId     资源id
     */
    public void setCloseImg(@DrawableRes int resId) {
        ivCloseBtn.setImageResource( resId );
    }

    /**
     * 设置标题内容
     * @param title     标题
     */
    public void setTitle(String title) {
        tvTitle.setText( title );
    }

    /**
     * 设置标题内容大小，默认使用{@link android.util.TypedValue#COMPLEX_UNIT_SP}，
     * 详细设置可以使用{@link #getTitleView()}
     * @param size      大小
     */
    public void setTitleTextSize(float size) {
        tvTitle.setTextSize( size );
    }

    /**
     * 设置关闭按钮的大小
     * @param width     宽度
     * @param height    高度
     */
    public void setCloseBtnSize(int width, int height) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) ivCloseBtn.getLayoutParams();
        lp.width = width;
        lp.height = height;
        ivCloseBtn.setLayoutParams( lp );
    }
    public void setCloseBtnSize(int size) {
        setCloseBtnSize(size, size);
    }

    /**
     * 设置点击关闭按钮事件监听器
     * @param listener  监听器
     */
    public void setOnClickCloseListener(View.OnClickListener listener) {
        mOnClickCloseListener = listener;
    }

    /**
     * 设置选择分支回调监听器
     * 因为当前dialog调用了{@link CityPickerView}下的
     * {@link CityPickerView#setOnSelectBranchListener(CityPickerView.OnSelectBranchListener)}方法，
     * 因为直接调用，自动关闭会失效，所以这里重新监听该方法。
     * @param listener  监听器
     */
    public void setOnSelectBranchListener(CityPickerView.OnSelectBranchListener listener) {
        mOnSelectBranchListener = listener;
    }

    /**
     * 获取标题控件
     * @return  {@link TextView}
     */
    public TextView getTitleView() {
        return tvTitle;
    }

    /**
     * 获取关闭按钮
     * @return  {@link ImageView}
     */
    public ImageView getCloseBtn() {
        return ivCloseBtn;
    }

    /**
     * 获取城市选择器
     * @return  {@link CityPickerView}
     */
    public CityPickerView getCityPickerView() {
        return cpvCityPicker;
    }
}
